<template>
  <view class="chat-page">
    <up-popup
      :show="msgsPopup"
      mode="right"
      @close="closeHistory"
      @open="showHistory">
      <view class="popup-content">
        <view class="popup-header">
          <u-status-bar></u-status-bar>
          <text class="popup-title">历史记录</text>
        </view>
        <view class="new-chat" @click="startNewChat">
          <up-icon name="plus" size="20" color="#6ab5ff"></up-icon>
          <text class="new-chat-text">新建对话</text>
        </view>
        <scroll-view scroll-y="true" class="history-list">
          <view
            v-for="(history, idx) in chatHistory"
            :key="history.id"
            class="history-item">
            <view class="history-content" @click="loadChatHistory(idx)">
              <up-icon name="chat" size="20" color="#666666"></up-icon>
              <text class="history-text">{{ history.title }}</text>
            </view>
            <view
              class="history-actions"
              @click.stop="deleteChatHistory(history.id)">
              <up-icon name="trash" size="20" color="#ff4d4f"></up-icon>
            </view>
          </view>
        </scroll-view>
      </view>
    </up-popup>
    <view class="container">
      <!-- 聊天头部 -->
      <view class="header">
        <u-status-bar></u-status-bar>
        <view class="header-content">
          <up-icon name="home" size="24" color="#fff" @click="goHome"></up-icon>
          <text class="title">中草药智能助手</text>
          <up-icon
            name="chat"
            size="24"
            color="#fff"
            @click="showHistory"></up-icon>
        </view>
      </view>
      <!-- 聊天内容区域 -->
      <scroll-view
        ref="chatContainerRef"
        class="chat-container"
        scroll-y
        :scroll-top="scrollTop"
        refresher-enabled
        :style="{ marginBottom: (148 + keyboardHeight * 2) + 'rpx' }"
        @refresherrefresh="loadMore">
        <view
          v-for="(msg, index) in messages"
          :key="index"
          class="message-wrapper"
          :class="[msg.role]">
          <!-- 用户头像 -->
          <view v-if="msg.role === 'user'" class="avatar user-avatar">
            <up-icon name="account" size="31" color="#515151"></up-icon>
          </view>
          <!-- AI头像 -->
          <view v-if="msg.role === 'ai'" class="avatar ai-avatar">
            <up-icon
              name="http://www.adnaan.cn/chinese-images/svg/robot.svg"
              size="31"
              color="#515151"></up-icon>
          </view>
          <!-- 消息气泡 -->
          <view class="message-bubble" :class="{ thinking: msg.thinking }">
            <text v-if="msg.content" class="message-text">
              {{ msg.content }}
            </text>
            <view v-if="msg.thinking" class="thinking-dots">
              <view class="dot"></view>
              <view class="dot"></view>
              <view class="dot"></view>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 输入区域 -->
      <view class="input-container" :style="{ bottom: keyboardHeight + 'px' }">
        <view class="input-wrapper">
          <up-input
            class="input-box"
            type="text"
            v-model="inputText"
            placeholder="请输入您的问题"
            :adjust-position="false" 
            @confirm="sendMessage" />
          <button
            class="send-btn"
            :disabled="!inputText.trim()"
            @click="sendMessage">
            <up-icon
              name="http://www.adnaan.cn/chinese-images/icon/send.png"
              size="24"
              color="#FFFFFF"></up-icon>
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, nextTick, onUnmounted, onMounted } from "vue";
import AIChatWebSocket from "@/utils/websocket";
import {
  addChatHistory_api,
  deleteChatHistory_api,
  getMyChatHistory_api,
  saveChatHistory_api,
} from "@/api/api";

const messages = reactive([]);
const inputText = ref("");
const sending = ref(false);
const scrollTop = ref(0);
const chatContainerRef = ref(null);
const wsClient = ref(null);
const msgsPopup = ref(false);
const chatHistory = ref([]);
const currentChatId = ref(null);
const keyboardHeight = ref(0);

// 加载聊天历史
const loadChatHistories = async () => {
  try {
    const response = await getMyChatHistory_api();
    if (response.code === 200) {
      chatHistory.value = response.data.map((history) => ({
        ...history,
        messages: history.messages,
      }));
    }
  } catch (error) {
    console.error("加载历史记录失败:", error);
    uni.showToast({
      title: "加载历史记录失败",
      icon: "none",
    });
  }
};

// 保存当前聊天记录
const saveChatHistory = async (title = null) => {
  if (messages.length === 0) return;

  try {
    const userId = uni.getStorageSync("userId");
    const historyData = {
      id: currentChatId.value,
      title: title || messages[1].content.substring(0, 10) + "...",
      messages: messages,
      userId,
    };
    let response = null;
    if (!currentChatId.value) {
      delete historyData.id;
      response = await addChatHistory_api(historyData);
    } else {
      response = await saveChatHistory_api(historyData);
    }

    if (response.code === 200) {
      await loadChatHistories();
    }
  } catch (error) {
    console.error("保存聊天记录失败:", error);
    uni.showToast({
      title: "保存失败",
      icon: "none",
    });
  }
};

// 加载特定的聊天记录
const loadChatHistory = async (index) => {
  const history = chatHistory.value[index];
  messages.length = 0; // 清空当前消息
  console.log(history.messages);
  messages.push(...history.messages);
  currentChatId.value = history.id;
  msgsPopup.value = false;
};

// 开始新对话
const startNewChat = () => {
  messages.length = 0;
  currentChatId.value = null;
  messages.push({
    role: "ai",
    content: "您好！我是中草药智能助手，很高兴为您服务。请问有什么可以帮您？",
    thinking: false,
  });
  msgsPopup.value = false;
};

// 删除聊天记录
const deleteChatHistory = async (id) => {
  try {
    const response = await deleteChatHistory_api({ id: id });

    if (response.code === 200) {
      await loadChatHistories();
      if (currentChatId.value === id) {
        startNewChat();
      }
      uni.showToast({
        title: "删除成功",
        icon: "success",
      });
    }
  } catch (error) {
    console.error("删除聊天记录失败:", error);
    uni.showToast({
      title: "删除失败",
      icon: "none",
    });
  }
};

// 在发送消息后自动保存
const sendMessage = async () => {
  if (!inputText.value.trim() || sending.value) return;
  // 检查websocket是否连接
  messages.push({
    role: "user",
    content: inputText.value.trim(),
  });

  const prompt = inputText.value;
  inputText.value = "";
  sending.value = true;

  try {
    await streamResponse(prompt);
  } finally {
    sending.value = false;
  }
};

onMounted(() => {
  wsClient.value = new AIChatWebSocket();
  loadChatHistories(); // 加载历史记录
  startNewChat(); // 开始新对话
  
  // 监听键盘高度变化
  uni.onKeyboardHeightChange(res => {
    nextTick(() => {
      keyboardHeight.value = res.height;
    });
  });
});

onUnmounted(() => {
  // 组件卸载时关闭连接
  if (wsClient.value) {
    wsClient.value.close();
  }
});

// 真实流式请求
const streamResponse = async (prompt) => {
  const aiMessage = reactive({
    role: "ai",
    content: "",
    thinking: true,
  });
  messages.push(aiMessage);

  try {
    // 设置消息处理回调
    wsClient.value.handleStreamResponse({
      onMessage: (data) => {
        console.log("收到消息:", data);
        if (data && data.content) {
          aiMessage.content += data.content;
          // 强制更新视图
          nextTick(() => {
            scrollTop.value = chatContainerRef.value?.scrollHeight || 0;
          });
        }
      },
      onError: (error) => {
        console.error("AI对话错误:", error);
        aiMessage.content += "\n（连接服务失败）";
        aiMessage.thinking = false;
      },
      onComplete: () => {
        console.log("对话完成");
        nextTick(() => {
          aiMessage.thinking = false;
          // 自动保存聊天记录
          saveChatHistory();
          scrollTop.value = chatContainerRef.value?.scrollHeight || 0;
        });
      },
    });

    // 发送消息
    await wsClient.value.sendMessage(prompt);
  } catch (error) {
    console.error("连接失败:", error);
    aiMessage.content += "\n（连接服务失败）";
    aiMessage.thinking = false;
  }
};

const loadMore = () => {
  // 这里可以实现加载更多历史消息的逻辑
  console.log("加载更多消息");
};

const showHistory = () => {
  msgsPopup.value = true;
};
const closeHistory = () => {
  msgsPopup.value = false;
};

const goHome = () => {
  uni.switchTab({
    url: "/pages/index/index",
  });
};
</script>
<style scoped lang="scss">
.chat-page {
  width: 100%;
  height: 100vh;
}
.container {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f7fb;
}

.header {
  position: fixed; /* 改为固定定位 */
  width: 100%;
  z-index: 999;
  top: 0;
  left: 0;
  box-sizing: border-box;
  padding: 40rpx 30rpx;
  background-color: #ffffff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  flex-shrink: 0;
  border-bottom-left-radius: 30rpx;
  border-bottom-right-radius: 30rpx;
  background: linear-gradient(135deg, #4a90e2 3%, #6ab5ff 100%);
  backdrop-filter: blur(20rpx);

  .header-content {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 40rpx;
    .title {
      font-size: 42rpx;
      color: #ffffff;
      font-weight: bold;
    }
  }
}

.popup-content {
  width: 600rpx;
  height: 100%;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
}
.popup-header {
  padding: 60rpx 30rpx 70rpx 30rpx;
  background: linear-gradient(135deg, #4a90e2 3%, #6ab5ff 100%);
  border-bottom: 1px solid #eeeeee;
}
.popup-title {
  font-size: 16px;
  font-weight: 600;
  color: #fff;
}
.new-chat {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx;
  background: rgba(0, 87, 255, 0.06);
  border: 1rpx solid rgba(0, 102, 255, 0.15);
}
.new-chat-text {
  font-size: 28rpx;
  color: #6ab5ff;
  margin-left: 10rpx;
}
.history-list {
  flex: 1;
  overflow: auto;
}
.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1px solid #f5f5f5;
  transition: all 0.3s ease;

  .history-content {
    display: flex;
    align-items: center;
    gap: 20rpx;
    flex: 1;
  }

  .history-actions {
    transition: opacity 0.3s ease;
    background-color: #f8f9fe;
  }

  &:active {
    background-color: #f5f5f5;
  }
}
.history-text {
  font-size: 28rpx;
  color: #666666;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-container {
  flex: 1;
  padding: 20rpx;
  box-sizing: border-box;
  overflow-y: auto;
  margin-top: 245rpx; /* 为header预留空间 */
  margin-bottom: 148rpx; /* 为input-container预留空间 */
}

.message-wrapper {
  margin: 20rpx 0;
  display: flex;
  align-items: flex-start;

  &.user {
    justify-content: flex-end;

    .message-bubble {
      background: #1890ff;
      color: white;
      border-radius: 16rpx 16rpx 0 16rpx;
    }
    .avatar {
      order: 2;
      margin-left: 20rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }
  }

  &.ai {
    justify-content: flex-start;

    .message-bubble {
      background: white;
      color: #333;
      border-radius: 16rpx 16rpx 16rpx 0;
    }
    .avatar {
      order: 0;
      margin-right: 20rpx;
    }
  }
}

.avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  overflow: hidden;
  image {
    width: 100%;
    height: 100%;
  }
}

.message-bubble {
  max-width: 70%;
  padding: 20rpx 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  position: relative;
  min-height: 40rpx;

  &.thinking {
    padding: 30rpx 40rpx;
  }
}
.input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 30rpx 40rpx;
  background-color: #ffffff;
  border-top: 1px solid rgba(238, 238, 238, 0.6);
  flex-shrink: 0;
  backdrop-filter: blur(10px);
  box-sizing: border-box;
  z-index: 999;
}
.input-wrapper {
  display: flex;
  gap: 20rpx;
  align-items: center;
}
.input-box {
  flex: 1;
  height: 88rpx;
  background-color: #f5f7ff;
  border-radius: 44rpx;
  padding: 0 40rpx;
  font-size: 14px;
  color: #333333;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}
.input-box:focus {
  border-color: rgba(76, 175, 80, 0.3);
  background-color: #ffffff;
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.1);
}
.send-btn {
  width: 88rpx;
  height: 88rpx;
  border-radius: 44rpx;
  background: linear-gradient(135deg, #4a90e2, #6ab5ff);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.2);
  transition: all 0.3s ease;
}
.send-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2px 6px rgba(76, 175, 80, 0.15);
}
.send-btn[disabled] {
  opacity: 0.7;
}

// 思考动画
.thinking-dots {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40rpx;

  .dot {
    width: 12rpx;
    height: 12rpx;
    margin: 0 6rpx;
    background: #ddd;
    border-radius: 50%;
    animation: dot-pulse 1.4s infinite ease-in-out;

    &:nth-child(2) {
      animation-delay: 0.2s;
    }

    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes dot-pulse {
  0%,
  80%,
  100% {
    transform: scale(0.6);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

// 消息进入动画
.message-wrapper {
  opacity: 0;
  transform: translateY(20rpx);
  animation: messageAppear 0.3s ease forwards;
}

@keyframes messageAppear {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-text {
  word-break: break-all;
  white-space: pre-wrap;
}
</style>